package com.egan.pet.admin.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.egan.entity.dto.UserDTO;
import com.egan.entity.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author NoobMaster69  * @date 2024/12/3 0003 星期二 13:43
 */
@Service
public class AuthService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String LOGIN_USER_KEY = "login_user:";
    private static final long LOGIN_USER_TTL = 30; // Token有效期30分钟

    /**
     * 生成Token并将用户信息保存到Redis
     *
     * @param user 用户对象
     * @return 生成的Token
     */
    public String generateAndSaveToken(User user) {
        // 1. 随机生成TOKEN
        String token = UUID.randomUUID().toString();

        // 2. 将User对象转为HashMap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        // 3. 存储到Redis
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);

        // 4. 设置token的有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        return token;
    }
}
